<template>
	<uni-popup ref="popup" :type="mode" :mask-click="true" :style="popupStyle" class="detail-popup-container">
		<view v-if="item && item.Name" class="popup-content" :class="{'dark-theme': darkMode}">
			<view class="popup-header">
				<view class="popup-title">
					<text class="popup-name">{{ item.Name }}</text>
					<uni-icons type="close" size="20" @click="close" :color="darkMode ? '#fff' : '#000'"
						class="close-icon"></uni-icons>
				</view>
				<view class="option-area">
					<view class="option-item">
						<delmodule v-if="item.CanDelete" @click="clickDelete(item)" />
						<text style="font-size: 0.6rem;">删除</text>
					</view>
					<view class="option-item">
						<collect :isLike="item.UserData.IsFavorite" @click="clickLike(item)" />
						<text style="font-size: 0.6rem;">收藏</text>
					</view>
					<view class="option-item" v-if="item.Type=='Video' || item.Type=='Movie'">
						<view>
							<image class="play-image" style="width: 16px;height: 16px;" src="@/static/play1_w.png"
								@click="handlePlayVideo"></image>
						</view>
						<text style="font-size: 0.6rem;">播放</text>
					</view>
				</view>
			</view>
			  <scroll-view class="popup-body" :scroll-y="true" :style="scrollViewStyle" :show-scrollbar="false"
			   scroll-with-animation @touchmove.stop.prevent="handleScroll">
				<view class="people-section" style="margin-top: 10px;"
					v-if="moreMediaInfo && moreMediaInfo.People && moreMediaInfo.People.length>0">
					<text class="label" style="font-size: 0.8rem;">演职人员：</text>
					<view class="people-container">
						<view class="people-item" @click="clickSearchPeople(item)" v-for="(item,index) in moreMediaInfo.People" :key="index">
							<image class="image" :src="item.PrimaryImageUrl" mode="aspectFill" style="
							    width: 120upx;
							    height: 120upx;
							    margin-top: 10upx;"></image>
							<text style="font-size: 0.6rem;">{{item.Name}}</text>
						</view>
					</view>
				</view>
				<view class="similar-section" style="margin-top: 10px;" v-if="setMediaList && setMediaList.length>0">
					<text class="label" style="font-size: 0.8rem;">所属合集：</text>
					<view class="search-result">
						<scroll-view show-scrollbar="false" scroll-x="true" style="width: 100%; white-space: nowrap; overflow: auto;">
							<horizontal :list="setMediaList" :httpParams="setHttpParams" @open-detailPopup="openSetMediaDetailPopup" />
						</scroll-view>
					</view>
				</view>
				<view class="similar-section" style="margin-top: 10px;" v-if="similarMediaList && similarMediaList.length>0">
					<text class="label" style="font-size: 0.8rem;">相似推荐：</text>
					<view class="search-result">
						<scroll-view show-scrollbar="false" scroll-x="true" style="width: 100%; white-space: nowrap; overflow: auto;">
							<horizontal :list="similarMediaList" :httpParams="httpParams" @open-detailPopup="openSimilarMediaDetailPopup" />
						</scroll-view>
					</view>
				</view>
				<view class="tags-section" style="margin-top: 10px;" v-if="checkDicts && checkDicts.length>0">
					<text class="label" style="font-size: 0.8rem;">标签：</text>
					<div class="tags-container" style="display: flex;align-items: center;">
						<uni-data-checkbox mode="tag" multiple v-model="selectCheckbox" :localdata="checkDicts"
							:style="{ '--color': darkMode ? '#4CAF50' : '#2979ff' }"></uni-data-checkbox>
						<button class="search-tags-btn" @click="clickSearchByTags" :class="{'dark-theme': darkMode}"
							v-if="selectCheckbox.length>0">
							<uni-icons type="search" :color="darkMode ? '#fff' : '#fff'" size="16"
								class="btn-icon"></uni-icons>
							搜索
						</button>
					</div>
				</view>
				<view class="genres-section" style="margin-top: 10px;" v-if="genresList && genresList.length>0">
					<text class="label" style="font-size: 0.8rem;">风格：</text>
					<div class="genres-container" style="display: flex;align-items: center;">
						<uni-data-checkbox mode="tag" multiple v-model="selectGenCheckbox" :localdata="genresList"
							:style="{ '--color': darkMode ? '#4CAF50' : '#2979ff' }"></uni-data-checkbox>
						<button class="search-tags-btn" @click="clickSearchByGens" :class="{'dark-theme': darkMode}"
							v-if="selectGenCheckbox.length>0">
							<uni-icons type="search" :color="darkMode ? '#fff' : '#fff'" size="16"
								class="btn-icon"></uni-icons>
							搜索
						</button>
					</div>
				</view>
				<view class="media-section" style="margin-top: 10px;">
					<text class="label" style="font-size: 0.8rem;">媒体信息：</text>
					<view class="info-item" v-if="moreMediaInfo.Path">
						<text class="label">路径：</text>
						<text class="value">{{ moreMediaInfo.Path }}</text>
					</view>
					<view class="info-item" v-if="item.Size">
						<text class="label">大小：</text>
						<text class="value">{{ formattedSize(item.Size) }}</text>
					</view>
					<view class="info-item" v-if="item.Width && item.Height">
						<text class="label">分辨率：</text>
						<text class="value">{{ formattedRes(item.Width, item.Height) }}</text>
					</view>
					<view class="info-item" v-if="item.DateCreated">
						<text class="label">创建日期：</text>
						<text class="value">{{ formattedDate(item.DateCreated) }}</text>
					</view>
				</view>
			  </scroll-view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		videoDataFormatter
	} from "@/common/videoDataFormatter.js";
	import collect from '@/components/collect.vue'
	import delmodule from '@/components/delete.vue'
	import horizontal from '@/components/horizontal.vue'
	import request from '@/common/request'

	export default {
		name: 'DetailPopup',
		components: {
			collect,
			delmodule,
			horizontal
		},
		props: {
			item: {
				type: Object,
				default: () => ({})
			},
			mode: {
				type: String,
				default: 'right',
				validator: (val) => ['center', 'right', 'bottom'].includes(val)
			},
			darkMode: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				checkDicts: [],
				selectCheckbox: [],
				navBarTop: undefined,
				navBarHeight: undefined,
				moreMediaInfo: {},
				similarMediaList: [],
				httpParams: {},
				setMediaList: [],
				setHttpParams: {},
				genresList: [],
				selectGenCheckbox: [],
			}
		},
		watch: {
			item: {
				deep: true,
				handler(newVal) {
					this.moreMediaInfo = {};
					this.similarMediaList = [];
					this.setMediaList = [];
					if (!newVal || !newVal.Id) {
						return;
					}
					this.initTags(newVal)
					this.getMoreMediaInfo(newVal)
					this.getSimilarMedia(newVal)
					this.getOwerSet(newVal)
				}
			}
		},
		computed: {
			popupStyle() {
				return this.mode === 'right' ? {
					width: '80%',
					maxWidth: '500px',
					maxHeight: '90vh',
					display: 'flex',
					flexDirection: 'column'
				} : {}
			},
			scrollViewStyle() {
				return {
					// 使用flex布局计算剩余空间
					flexGrow: 1,
					// overflowY: 'auto',
					// 确保有最小高度
					minHeight: '100px',
					maxHeight: '75vh',
					// 添加内边距避免内容紧贴边缘
					paddingBottom: '20px'
				}
			}
		},
		created() {
			this.navBarTop = uni.getSystemInfoSync().statusBarHeight + "px";
			this.navBarHeight = 44 + uni.getSystemInfoSync().statusBarHeight + "px";
		},
		methods: {
			handleScroll(e) {
				// 阻止事件冒泡到父元素
				e.stopPropagation();
			},
			initTags(item) {
				this.checkDicts = []
				this.selectCheckbox = []
				if (item.TagItems && item.TagItems.length > 0) {
					this.checkDicts = item.TagItems.map(tag => ({
						text: tag.Name,
						value: tag.Id
					}))
				}
			},
			initGenresList(item) {
				this.genresList = []
				this.selectGenCheckbox = []
				if (item.GenreItems && item.GenreItems.length > 0) {
					this.genresList = item.GenreItems.map(t => ({
						text: t.Name,
						value: t.Id
					}))
				}
			},
			open() {
				this.$refs.popup.open();
			},
			close() {
				this.$refs.popup.close()
			},
			formattedSize(videoSize) {
				return videoDataFormatter.formatVideoSize(videoSize)
			},
			formattedRes(width, height) {
				return videoDataFormatter.formatResolution(width, height)
			},
			formattedDate(date) {
				return videoDataFormatter.formatDate(date, 'YYYY-MM-DD')
			},
			handlePlayVideo() {
				this.$store.dispatch('saveLargeList', {
					data: [this.item],
					index: 0,
					httpParams: {}
				}).then(()=>{
					uni.navigateTo({
						url: `/pages/player/app/short`
					})
				})
			},
			clickSearchByTags() {
				const outTags = this.checkDicts
					.filter(ck => this.selectCheckbox.includes(ck.value))
					.map(ck => ({
						Id: ck.value,
						Name: ck.text
					}))

				if (outTags.length > 0) {
					this.$emit('searchByTags', outTags)
					this.close()
				}
			},
			clickSearchByGens() {
				const outGens = this.genresList
					.filter(ck => this.selectGenCheckbox.includes(ck.value))
					.map(ck => ({
						Id: ck.value,
						Name: ck.text
					}))
			
				if (outGens.length > 0) {
					this.$emit('searchByGens', outGens)
					this.close()
				}
			},
			clickSearchPeople(people) {
				this.$emit('searchByPeople', people)
				this.close()
			},
			openSetMediaDetailPopup(videoItem){
				this.$emit('clickSetMedia', videoItem)
			},
			openSimilarMediaDetailPopup(videoItem){
				this.$emit('clickSimilarMedia', videoItem)
			},
			clickDelete(videoItem) {
				// 删除 视频
				uni.showModal({
					title: '确定删除？',
					content: '删除后源文件将被删除',
					success: (re) => {
						if (re.confirm) {
							uni.showLoading({
								title: '正在删除'
							})
							request.post(`/emby/Items/Delete?Ids=${videoItem.Id}&`).finally(() => {
								uni.hideLoading();
								// 从数组中删除该元素
								// console.log("从数组中删除该元素"+videoItem.Id)
								this.$store.commit('delVideoId', videoItem.Id);
								this.close()
							})
						}
					}
				})
			},

			clickLike(videoItem) {
				let userTmp1 = uni.getStorageSync('user')
				if (!userTmp1) {
					return
				}
				let userTmp = JSON.parse(userTmp1)
				let fav = videoItem.UserData.IsFavorite;
				if (fav) {
					// 取消收藏
					request.post(`/emby/Users/${userTmp.userId}/FavoriteItems/${videoItem.Id}/Delete`)
					videoItem.UserData.IsFavorite = false
					return
				}
				// 取消收藏
				request.post(`/emby/Users/${userTmp.userId}/FavoriteItems/${videoItem.Id}`)
				videoItem.UserData.IsFavorite = true
			},
			async getMoreMediaInfo(item) {
				let userTmp1 = uni.getStorageSync('user')
				let userTmp = JSON.parse(userTmp1)
				let getJSON = {
					fields: "ShareLevel",
					ExcludeFields: "VideoChapters,VideoMediaSources,MediaStreams"
				}
				let urlAppend = this.$g.jsonToGetParams(getJSON)
				let moreMediaInfoTmp = await request.get(`/emby/Users/${userTmp.userId}/Items/${item.Id}${urlAppend}`)
				let serverUrl = `${userTmp.serverip}:${userTmp.serverport}`
				if (!serverUrl.startsWith('http')) {
					serverUrl = `http://${serverUrl}`
				}
				if (moreMediaInfoTmp.People) {
					for (let moreItem of moreMediaInfoTmp.People) {
						if (moreItem.Id) {
							let imageStr = `${serverUrl}/emby/Items/${moreItem.Id}/Images/Primary`
							moreItem.PrimaryImageUrl = imageStr
						}
					}

				}
				this.moreMediaInfo = moreMediaInfoTmp
				this.initGenresList(this.moreMediaInfo)
			},
			async getSimilarMedia(item) {
				let userTmp1 = uni.getStorageSync('user')
				let userTmp = JSON.parse(userTmp1)
				let getJSON = {
					Limit: 50,
					UserId: userTmp.userId,
					ImageTypeLimit: 1,
					Fields: "BasicSyncInfo,CanDelete,CanDownload,PrimaryImageAspectRatio,ProductionYear,Status,EndDate",
					EnableTotalRecordCount: false
				}
				let urlAppend = this.$g.jsonToGetParams(getJSON)
				let mediaListTmp = await request.get(`/emby/Items/${item.Id}/Similar${urlAppend}`)
				let mediaList = mediaListTmp.Items || []
				// console.log(mediaList)
				let serverUrl = `${userTmp.serverip}:${userTmp.serverport}`
				if (!serverUrl.startsWith('http')) {
					serverUrl = `http://${serverUrl}`
				}
				for (const item of mediaList) {
					let imageStr = `${serverUrl}/emby/Items/${item.Id}/Images/Primary`
					item.cover = imageStr
				}
				this.httpParams = {
					params: getJSON,
					url: `/emby/Items/${item.Id}/Similar`
				}
				this.similarMediaList = mediaList
			},
			async getOwerSet(item) {
				let userTmp1 = uni.getStorageSync('user')
				let userTmp = JSON.parse(userTmp1)
				let getJSON = {
					Limit: 50,
					IncludeItemTypes: "Playlist,BoxSet",
					Recursive: true,
					Fields: "BasicSyncInfo,CanDelete,CanDownload,PrimaryImageAspectRatio,ProductionYear,Status,EndDate",
					SortBy: "SortName",
					ListItemIds: item.Id
				}
				let urlAppend = this.$g.jsonToGetParams(getJSON)
				let mediaListTmp = await request.get(`/emby/Users/${userTmp.userId}/Items${urlAppend}`)
				let mediaList = mediaListTmp.Items || []
				let serverUrl = `${userTmp.serverip}:${userTmp.serverport}`
				if (!serverUrl.startsWith('http')) {
					serverUrl = `http://${serverUrl}`
				}
				for (const item of mediaList) {
					let imageStr = `${serverUrl}/emby/Items/${item.Id}/Images/Primary`
					item.cover = imageStr
				}
				this.setHttpParams = {
					params: getJSON,
					url: `/emby/Users/${userTmp.userId}/Items`
				}
				this.setMediaList = mediaList
			}
		}
	}
</script>

<style lang="scss" scoped>
	.popup-content {
		background-color: #fff;
		border-radius: 12px;
		padding: 20px;
		box-sizing: border-box;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
		transition: background-color 0.3s ease;
		display: flex;
		flex-direction: column;
		height: 85vh;

		&.dark-theme {
			background-color: #353535;
			color: #fff;
			box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
		}
	}

	.popup-header {
		flex-shrink: 0;
		padding-bottom: 16px;
		border-bottom: 1px solid #f0f0f0;
		margin-bottom: 20px;
		
		.dark-theme & {
			border-bottom-color: #4a4a4a;
		}
	}

	.popup-title {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.dark-theme & {
			border-bottom-color: #4a4a4a;
		}
	}

	.popup-name {
		font-size: 0.8rem;
		font-weight: 600;
		transition: font-size 0.2s ease;
		line-height: 1.3;
	}

	.close-icon {
		cursor: pointer;
		transition: transform 0.2s ease, opacity 0.2s ease;

		&:hover {
			transform: scale(1.1);
			opacity: 0.8;
		}
	}

	.info-item {
		display: flex;
		align-items: center;
		padding: 3px 0;
		border-radius: 6px;
		transition: background-color 0.2s ease;

		&:hover {
			background-color: #f9f9f9;

			.dark-theme & {
				background-color: #404040;
			}
		}
	}

	.label {
		width: 80px;
		flex-shrink: 0;
		color: #666;
		font-size: 0.7rem;
		transition: color 0.3s ease;

		.dark-theme & {
			color: #bbb;
		}
	}

	.value {
		flex: 1;
		color: #333;
		font-size: 0.75rem;
		line-height: 1.5;
		transition: color 0.3s ease;

		.dark-theme & {
			color: #ddd;
		}
	}

	.tags-section {
		margin-top: 20px;
		padding-top: 16px;
		border-top: 1px dashed #eee;

		.dark-theme & {
			border-top-color: #4a4a4a;
		}

		.label {
			margin-bottom: 12px;
			display: block;
		}
	}

	.tags-container {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		align-items: center;
		padding: 8px 0;
		margin-bottom: 8px;
	}

	.search-icon {
		cursor: pointer;
		transition: transform 0.2s ease, opacity 0.2s ease;
		margin-left: 4px;

		&:hover {
			transform: scale(1.05);
			opacity: 0.9;
		}
	}

	// 优化标签样式
	::v-deep .checklist-text {
		border-radius: 6px;
		padding: 4px 10px;
		margin: 0 6px 6px 0;
		font-size: 0.65rem;
		transition: all 0.2s ease;
		border: 1px solid transparent;

		&:hover {
			transform: translateY(-1px);
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
		}
	}

	.search-tags-btn {
		padding: 0 3px;
		background-color: #2979ff;
		color: #fff !important;
		font-size: 0.7rem;
		display: inline-flex;
		align-items: center;
		gap: 6px;
		transition: all 0.2s ease;
		border: none;
		height: 20px;

		&:hover {
			background-color: #1a68e0;
			transform: translateY(-1px);
			box-shadow: 0 2px 8px rgba(41, 121, 255, 0.3);
		}

		&:disabled {
			background-color: #e0e0e0;
			cursor: not-allowed;
			transform: none;
			box-shadow: none;
		}

		&.dark-theme {
			background-color: #4CAF50;

			&:hover {
				background-color: #3d9140;
				box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
			}

			&:disabled {
				background-color: #555;
			}
		}

		.btn-icon {
			vertical-align: middle;
		}
	}

	::v-deep .checklist-text {
		color: #fff;
		font-size: 0.6rem !important;
		padding: 2px;

		&:hover {
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		}
	}
	
	::v-deep .checklist-content {
		border-radius: 4px;
	}

	::v-deep .checklist-box.is--checked {
		transform: translateY(-1px);
	}

	::v-deep .checklist-box.is--tag {
		padding: 0 !important;
		border: none !important;
		border-radius: 3px !important;
	}

	.option-area {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		margin-top: 17px;
	}

	.option-area .option-item {
		display: flex;
		flex-flow: column;
		align-items: center;
		justify-content: center;
		margin-right: 20px;
	}

	::v-deep .collect-content {
		margin-top: 0 !important;
		margin-left: 0;
	}

	::v-deep .collect-content .collect-image {
		width: 19px !important;
		height: 16px !important;
	}

	::v-deep .delete-content {
		margin-top: 0 !important;
	}

	::v-deep .delete-content .delete-image {
		width: 16px !important;
		height: 16px !important;
		margin-bottom: 0 !important;
	}

	.people-section .people-item {
		display: flex;
		flex-flow: column;
		justify-content: center;
		align-items: center;
		margin-right: 20px;
	}

	.people-container {
		display: flex;
		flex-flow: row;
		flex-wrap: wrap;
	}

	.people-container .image {
		border-radius: 5px;
		box-shadow: 2px 2px 6px #333;
		background-image: url('@/static/default.jpg');
		background-repeat: no-repeat;
		background-position: center center;
		background-size: initial;
		width: 100%;
		height: 100%;
		object-fit: cover;
		border-radius: 4px;
		background-position: center center;
		background-size: 100% 100%;
	}
	
	.popup-body {
		// 关键：移除固定高度，使用flex自动填充
		// overflow-y: auto;
		// iOS滚动优化
		-webkit-overflow-scrolling: touch;
		// 解决滚动卡顿
		transform: translateZ(0);
		-webkit-transform: translateZ(0);
	}
	
	::v-deep .popup-body::-webkit-scrollbar {
		display: none;
	}
	
	.search-result {
	  width: 100%;
	  overflow: auto;
	}
	
	::v-deep .search-result {
	  width: 100%;
	  overflow: visible;
	}
	
	::v-deep .horizontalbox {
	  width: auto !important;
	}
</style>